<template>
  <div class="group-management">
    <div class="left">
      <!-- <role-tree :treeList="baseData"></role-tree> -->
      <div
        v-for="(item, index) in baseData"
        :key="item.id"
        :class="['item-nor', { 'item-active': index === activeIndex }]"
        @click="tabClick(item, index)"
      >
        {{ item.name }}
        <div>
          <!-- <Icon type="md-add" @click="append(item)"/> -->
          <Icon class="icon" v-if="item.id != 1" type="md-create" @click="openUpdate(item)" />
          <Icon class="icon" v-if="item.id != 1" type="ios-trash" @click="openDelete(item)" />
        </div>
      </div>
      <div class="footer-btn">
        <Button type="success" class="btn-save" @click="append">新建角色</Button>
      </div>
    </div>
    <div class="right">
      <!-- <base-form :formList="formList"></base-form> -->
      <div class="table">
        <Tabs v-model="tabName" :animated="false">
          <Tab-pane label="角色权限" name="1">
            <div class="message">
              <img class="img1" src="~_img/title-tip.png" alt="" />
              <img class="img2" src="~_img/title-tip.png" alt="" />
              {{ TabData.name }}
            </div>
            <div class="tree-box">
                <Tree
                  ref="TreeDom"
                  :data="treeData"
                  :render="renderContent"
                  show-checkbox
                  @on-check-change="getCheckedNodes"
                ></Tree>
              </div>
            <div class="footer" v-if="TabData.id !== 1">
              <Button @click="saveClick" type="success" class="btn-save">保存</Button>
              <Button class="btn-reset">取消</Button>
            </div>
          </Tab-pane>
        </Tabs>
      </div>
    </div>
    <validate-modal-form
      ref="roleModal"
      title="新增角色"
      @setForm="addrole"
      :formValidate="formValidate"
      :ruleValidate="ruleValidate"
      :formList="modalFormList"
    ></validate-modal-form>
    <validate-modal-form
      ref="roleUpdateModal"
      title="编辑角色"
      @setForm="updateRole"
      :formValidate="formValidate"
      :ruleValidate="ruleValidate"
      :formList="modalFormList"
    ></validate-modal-form>
  </div>
</template>

<script>
import IviewTable from '_c/iview/IviewTable'
import baseForm from '@/components/baseForm'
// import roleTree from './roleTree'
import validateModalForm from '_c/validateModalForm'
export default {
  name: 'roleManagement',
  components: {
    baseForm,
    IviewTable,
    // IviewModal,
    validateModalForm
  },
  data() {
    return {
      tabName: '1',
      TabData: {},
      addGroupModal: false,
      activeIndex: 0,
      formValidate: {
        name: '',
        description: '',
        enable: true,
        displayName: ''
      },
      ruleValidate: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      modalFormList: [
        // {
        //   type: 'input',
        //   label: '上级角色',
        //   model: 'displayName',
        //   readonly: true,
        //   placeholder: '请输入账号',
        // },
        {
          type: 'input',
          label: '角色名称',
          model: 'name',
          placeholder: '请输入角色名称'
        },
        {
          type: 'input',
          label: '角色描述',
          model: 'description',
          placeholder: '请输入角色描述'
        }
      ],
      page: {
        current: 1,
        pageSize: 40,
        total: 0
      },
      tableData: [],
      tableColumns: [
        {
          title: '组织名称',
          key: 'account'
        },
        {
          title: '上级组织',
          key: 'userName'
        },
        {
          title: '负责人',
          key: 'role'
        },
        {
          title: '联系电话',
          key: 'phone'
        },
        {
          title: '操作',
          key: 'action',
          //   fixed: 'right',
          width: 120,
          render() {
            return `<i-button type="text" size="small">编辑</i-button><i-button type="text" size="small">禁用</i-button>`
          }
        }
      ],
      baseData: [],
      mobileTreeData: [
        {
          expand: true,
          title: '数据概况',
          code: 'MOBILESURVEY'
        },
        {
          expand: true,
          title: '种植监测',
          code: 'MOBILEPLANT'
        },
        {
          expand: true,
          title: '仓储统计',
          code: 'MOBILESTORGE'
        }
      ],
      treeData: [
        {
          title: '账号管理',
          expand: true,
          code: 'ZHGL',
          children: [
            {
              title: '概况',
              expand: true,
              code: 'ZHGL_GK',
              childrens: [
                {
                  title: "导出",
                  expand: true,
                  code: "SJGL_DC",
                },
                {
                  title: "查看详情",
                  expand: true,
                  code: "SJGL_XQ",
                },
              ],
            },
            {
              title: '组织机构管理',
              expand: true,
              code: 'ZHGL_ZZJG'
            },
            {
              title: '角色权限管理',
              expand: true,
              code: 'ZHGL_JSQX'
            },
            {
              title: '用户管理',
              expand: true,
              code: 'ZHGL_YHGL'
            }
          ]
        }
      ],
      treeDomData: [],
      treeCode: [],
      codes: []
    }
  },
  mounted() {
    this.getRoleList()
    setTimeout(() => {
      console.log(this.treeData)
    }, 1000)
  },
  methods: {
    renderContent(h, { root, node, data }) {
      return h(
        'span',
        {
          on: {
            click: () => {}
          },
          style: {
            // display: 'flex',
            // width: '100%'
          }
        },
        [
          h(
            'span',
            {
              on: {
                click: () => {}
              },
              style: {
                display:'inline-block',
                width: '100px'
              }
            },
            data.title
          ),
          h(
            'CheckboxGroup',
            {
              props: {
                value: data.codes
              },
              on: {
                'on-change': (val) => {
                  data.codes = val
                  if (data.childrens.length === val.length) {
                    data.selected = true
                    data.checked = true
                  } else {
                    // data.selected = false
                    // data.checked = false
                  }
                }
              },
              style: {
              }
            },
            (data.childrens || []).map((item) =>
              h(
                'Checkbox',
                {
                  props: {
                    label: item.code
                  },
                  style: {
                    color: '#2c3542!important',
                    fontWeight: '400',
                    minWidth: '80px'
                  }
                },
                item.title
              )
            )
          )
        ]
      )
    },
    getCheckedNodes(all, data) {
      if (data.checked) {
        data.codes = check(data.children || data.childrens || [])
      } else {
        data.codes = close(data.children || data.childrens || [])
      }
      // 遍历选中复选框
      function check(list) {
        return list.map((item) => {
          if (item.children) item.codes = check(item.children)
          if (item.childrens) item.codes = check(item.childrens)
          return item.code
        })
      }
      // 遍历取消复选框
      function close(list) {
        list.map((item) => {
          if (item.children) item.codes = close(item.children)
          if (item.childrens) item.codes = close(item.childrens)
        })
        return []
      }
    },
    saveClick() {
      let data = this.$refs.TreeDom.getCheckedAndIndeterminateNodes()
      let dataRight = this.$refs.TreeDomRight.getCheckedAndIndeterminateNodes()
      let params = data.map((item) => item.code)
      data.map((item) => {
        if (item.childrens) {
          params.push(...item.codes)
        }
      })
      let paramsRight = dataRight.map((item) => item.code)
      dataRight.map((item) => {
        if (item.childrens) {
          paramsRight.push(...item.codes)
        }
      })
      this.$api.account
        .addRoleAction([...params, ...paramsRight], [this.TabData.id], {
          headers: { 'Content-Type': 'application/json' }
        })
        .then((res) => {
          this.$Message.success('添加成功')
        })
    },
    tabClick(item, index) {
      this.activeIndex = index
      this.TabData = item
      this.getResourcesRoleList()
    },
    addrole(data) {
      delete data.displayName
      this.$api.account.addRole(data, [0], { headers: { 'Content-Type': 'application/json' } }).then((res) => {
        // this.$set(this.treeDomData, 'children', children)
        this.$refs.roleModal.status = false
        this.getRoleList()
      })
    },
    updateRole(data) {
      delete data.displayName
      this.$api.account.updateRole(data, [this.treeDomData.id]).then((res) => {
        this.getRoleList()
        this.$refs.roleUpdateModal.status = false
      })
    },
    openUpdate(data) {
      this.treeDomData = data
      for (const key in data) {
        this.formValidate[key] = data[key]
      }
      this.$refs.roleUpdateModal.status = true
    },
    // 添加按钮
    append(data) {
      event.stopPropagation()
      //   this.treeDomData = data
      this.$refs.roleModal.status = true
    },
    openDelete(data) {
      this.$Modal.confirm({
        title: '提示',
        content: `您确定删除 “${data.name}” 吗？`,
        onOk: () => {
          this.$api.account.deleteRole({}, [0, data.id]).then((res) => {
            this.$Message.info('删除成功')
            this.getRoleList()
          })
        },
        onCancel: () => {
          //   this.$Message.info('取消')
        }
      })
    },
    getRoleList() {
      this.$api.account.getRoleList().then((res) => {
        this.baseData = res
        this.TabData = res[0]
        this.getResourcesRoleList()
      })
    },
    getResourcesRoleList() {
      this.treeCode = []
      this.$api.account.getResourcesRoleList({}, [this.TabData.id]).then((res) => {
        this.treeCode = res
        this.$nextTick(() => {
          this.defaultTreeData(this.treeData)
          this.defaultTreeData(this.mobileTreeData)
        })
      })
    },
    defaultTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children) {
          this.defaultTreeData(data[i].children)
        }
        if (!data[i].children && this.treeCode.includes(data[i].code)) {
          this.$set(data[i], 'checked', true)
        } else {
          this.$set(data[i], 'checked', false)
          this.$forceUpdate()
        }
        // 添加权限码
        let cs = data[i].childrens
        if (cs && cs.length > 0) {
          this.$set(data[i], 'codes', [])
          cs.map((item) => {
            if (this.treeCode.includes(item.code)) {
              data[i].codes.push(item.code)
            }
          })
        } else {
          this.$set(data[i], 'codes', [])
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tree-title {
  text-align: left;
  font-size: 14px;
  font-weight: bold;
  color: #828282;
}
.ivu-tree {
  text-align: left;
}
.message {
  margin-top: 8px;
  margin-left: 50%;
  transform: translateX(-50%);
  font-size: 14px;
  font-weight: bold;
  color: #828282;
  position: relative;
  display: inline-block;
  .img1,
  .img2 {
    position: absolute;
    top: 50%;
    transform: translateY(-50%) rotateY(180deg);
  }
  .img1 {
    left: -220px;
    transform: translateY(-50%);
  }
  .img2 {
    right: -220px;
  }
}
/deep/.ivu-tree {
  & > .ivu-tree-children {
    & > li {
      & > .ivu-tree-children {
        // display: inline-block;
        & > li {
          //    display: flex;
          .ivu-tree-children {
            // display: inline-block;
          }
        }
      }
    }
  }
}
// /deep/.ivu-tree-children{
//     display: flow-root;
// }
.group-management {
  position: relative;
  display: flex;
  justify-content: space-around;
  .left {
    width: 420px;
    background: #ffffff;
    padding: 40px 0 0 40px;
    position: relative;
    .footer-btn {
      position: absolute;
      bottom: 30px;
      left: 50%;
      transform: translateX(-50%);
      .btn-save {
        width: 100%;
        height: 30px;
        background: #85c989;
        box-shadow: 0px 2px 2px 0px #448247, 0px 0px 1px 0px #b4ffb9;
        font-size: 14px;
        font-weight: bold;
        color: #ffffff;
        text-shadow: 0px 1px 1px #163124, 0px 3px 5px #bcffca;
        margin-right: 30px;
        border: none;
      }
    }
    .item-nor {
      height: 24px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #2c3542;
      line-height: 24px;
      width: 240px;
      text-align: left;
      padding-left: 10px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 14px;
    }
    .item-active {
      color: #66bc7a;
      background: linear-gradient(90deg, rgba(243, 249, 243, 0) 0%, #e4f1e4 14%, rgba(228, 241, 228, 0) 100%);
    }
    .icon {
      font-size: 15px;
      margin-right: 10px;
      // background: #66BC7A;
    }
  }
  .right {
    // width: 1200px;
    flex: 0.99;
    background: #ffffff;
    padding-top: 20px;

    .table {
      padding: 0px 20px 0 20px;
      box-sizing: border-box;
      /deep/.ivu-tree {
        height: calc(70vh - 120px);
        overflow-y: auto;
      }
      .tree-box {
        display: flex;
        .right {
          padding-left: 10px;
        }
      }
      .footer {
        width: 98%;
        height: 98px;
        line-height: 98px;
        border-top: 2px solid #eceef0;
        margin: 20px 38px 0;
        box-sizing: border-box;
      }
    }
  }
}
/deep/.ivu-checkbox-group {
  display: inline-block;
}
</style>
